import numpy as np
import matplotlib.pyplot as plt
import sys,os
sys.path.append(os.pardir)
from common.functions import *
from common.gradient import numerical_gradient
from dataset.mnist import load_mnist

class TwoLayerNet:
    def __init__(self,input_size,hidden_size,output_size,weight_init_std = 0.01):
        # 初始化权重
        self.params = {}
        self.params['W1'] = weight_init_std * np.random.randn(input_size,hidden_size) # 以标准正态分布形式返回input_size * hidden_size大小的矩阵
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size,output_size)
        self.params['b2'] = np.zeros(output_size)
    def predict(self,x):
        W1,W2 = self.params['W1'], self.params['W2']
        b1,b2 = self.params['b1'], self.params['b2']
        a1 = np.dot(x,W1)+b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1,W2)+b2
        y = softmax(a2)
        return y
    def loss(self,x,t):
        # x -> 输入数据    t-> 正确标签
        y = self.predict(x)
        loss = cross_entropy_error(y,t)
        return loss
    def accuracy(self,x,t):
        y = self.predict(x)
        y = np.argmax(y,axis=1)
        # 通过argmax()获取值最大的元素的索引,给定了参数axis=1指定了在y的数组中，沿着第1维方向（以第1维为轴）找到值最大的元素的索引(第0维对应第1个维度)
        t = np.argmax(t,axis=1)
        accuracy = np.sum(y==t)/float(x.shape[0])
        return accuracy
    def numerical_gradient(self,x,t):
        loss_W = lambda W:self.loss(x,t)
        grads = {}
        grads['W1'] = numerical_gradient(loss_W,self.params['W1'])
        grads['b1'] = numerical_gradient(loss_W,self.params['b1'])
        grads['W2'] = numerical_gradient(loss_W,self.params['W2'])
        grads['b2'] = numerical_gradient(loss_W,self.params['b2'])
        return grads
    def gradient(self, x, t):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
        grads = {}
        
        batch_num = x.shape[0]
        
        # forward
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)
        
        # backward
        dy = (y - t) / batch_num
        grads['W2'] = np.dot(z1.T, dy)
        grads['b2'] = np.sum(dy, axis=0)
        
        da1 = np.dot(dy, W2.T)
        dz1 = sigmoid_grad(a1) * da1
        grads['W1'] = np.dot(x.T, dz1)
        grads['b1'] = np.sum(dz1, axis=0)

        return grads

(x_train,t_train),(x_test,t_test) = load_mnist(normalize = True,one_hot_label=True)
train_loss_list = []
train_acc_list = []
test_acc_list = []

# 超参数
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1

iter_per_epoch = max(train_size / batch_size, 1)
# epoch:一代训练，使用训练集的全部数据对模型进行一次完整训练
# 这里实际定义的大小为600，以后每更新600次，计算一次训练数据和测试数据的识别精度

network = TwoLayerNet(input_size=784,hidden_size=50,output_size=10)
print(t_train.shape[0])
for i in range(iters_num):
    # 获取mini_batch
    batch_mask = np.random.choice(train_size,batch_size)
    x_batch = x_train[batch_mask]
    t_batch = t_train[batch_mask]

    # 梯度计算
    # grad = network.numerical_gradient(x_batch,t_batch)
    grad = network.gradient(x_batch,t_batch)

    # 更新参数
    for key in ('W1','b1','W2','b2'):
        network.params[key] -= learning_rate * grad[key]
    # print(i,"次更新已经完成")
    loss = network.loss(x_batch,t_batch)
    # print(loss)
    train_loss_list.append(loss)
    if  i%iter_per_epoch == 0:
        train_acc = network.accuracy(x_train,t_train)
        test_acc = network.accuracy(x_test,t_test)
        train_acc_list.append(train_acc)
        test_acc_list.append(test_acc)
        print(train_acc,test_acc)


# plt.figure()
# plt.plot(train_loss_list)
# plt.show()
# print(train_loss_list)
x = np.arange(len(train_acc_list))
plt.plot(x,train_acc_list,label = 'train_acc')
plt.plot(x,test_acc_list,label = 'test_acc',linestyle = '--')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.ylim(0,1.0)
plt.legend(loc = 'lower right')
plt.show()
